package com.ciwong.epaper.modules.pad.homeworkwidget.common.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.support.v4.util.LruCache;
import android.util.DisplayMetrics;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

public class LruCacheCallBack {
    private  static  int thresholdPix=800*600;

    public static Bitmap bitmapCallMap(String key, Context context) {
        Bitmap bitmap = callMap(key, context);
        if (context!=null&&context.getResources()!=null){
            DisplayMetrics dm = context.getResources().getDisplayMetrics();
            if (dm != null)
                thresholdPix =thresholdPix< dm.widthPixels * dm.heightPixels?thresholdPix:dm.widthPixels * dm.heightPixels;
        }
        return compressBitmap(bitmap, thresholdPix);
    }

    private static Bitmap compressBitmap(Bitmap bitmap, int thresholdPix) {
        if (bitmap==null)return null;
        Bitmap bm = bitmap;
        int bitmapPix = bitmap.getWidth()*bitmap.getHeight();
        try {
            while (bitmapPix> thresholdPix){
                bm= compress(bm);
                bitmapPix = bm.getWidth()*bm.getHeight();
            }
        }catch (Exception e){
            e.printStackTrace();
            return bm;
        }
        return bm;
    }

    private static Bitmap compress(Bitmap bitmap){
        Matrix matrix = new Matrix();
        matrix.setScale(0.5f, 0.5f);
        Bitmap bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return bm;
    }

    public static Bitmap callMap(String key, Context context) {

        LruCache<String, Bitmap> lruBit = new LruCache<String, Bitmap>(
                ((int) (Runtime.getRuntime().maxMemory()) / 8)) {
            @Override
            protected int sizeOf(String key, Bitmap value) {

                return value.getByteCount();
            }
        };
        Bitmap bitmap = lruBit.get(key);

        if (bitmap == null) {
            bitmap = SDCardBitmap.getBitmapFromSD(key, context);
            if (bitmap == null) {
                URL picUrl = null;
                try {
                    picUrl = new URL(key);
                    bitmap = BitmapFactory.decodeStream(picUrl.openStream());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if (bitmap != null) {
                    lruBit.put(key, bitmap);
                    SDCardBitmap.setBitmapToSD(key, bitmap, context);
                }
            } else {
                lruBit.put(key, bitmap);
            }
        }
        return bitmap;
    }

}



